def initPlayerCastles
        $player_castles = []
        $browser.a(:title, $lang_countc).click
        
        index_beg = 0
        index_end = 0
        
        htmlfile = $browser.html
        
        name_identifier_beg = '<div><span class="habitatName">'
        name_identifier_end = '</span>'
        
        while true
                index_beg = htmlfile.index(name_identifier_beg,index_beg+1)
                if index_beg == nil
                        break
                end
                index_end = htmlfile.index(name_identifier_end,index_beg+1)
                index_end = index_end + name_identifier_end.length
                name = findString(htmlfile[index_beg..index_end],name_identifier_beg,name_identifier_end)
                playercastle = CPlayerCastle.new(name)
                $player_castles.push(playercastle)
        end
end

def init(debug=0)
	language
	$sorted.clear
	$castles.clear
	puts "initialize all castles. this may take some time..."
	$browser.a(:title, $lang_map).click
	sleep 3.0
	$browser.img(:id, 'centerHabitatButtonImage').click
	sleep 3.0
	htmlfile = $browser.html
	
	size = htmlfile.length
	
	tile_identifier =  '<div id="tile_'
	length = tile_identifier.length
	
	# indexing in htmlfile
	tile_index = []
	
	tile_top = []
	tile_left = []
	
	index = 0
	count = 0
	
	# extract tile line which looks like
	# <div id="tile_30" class="tileDiv" style="top:1008px;left:3024px;">
	# extracting data from tile
	while index < size
		index = htmlfile.index(tile_identifier,index+1)
		if index == nil
			break
		end
		tile_index.push(index)
		
		div_end = htmlfile.index('>',index+1)
		div_tile = htmlfile[index..div_end]

		tile_top  << findString(div_tile,'top:','px').to_i
		tile_left << findString(div_tile,'left:','px').to_i
		count = count + 1
	end
	#puts "found " + count.to_s + " tiles"
	
	# analyze coarse map
	columns = 0
	for i in 0 ... tile_top.size
		if tile_top[i] > 0
			columns = i
			break
		end
	end
	
	rows = count/columns
	puts "found " + count.to_s + " tiles with " + rows.to_s + " rows and " + columns.to_s + " columns"
	
	$tile_left_px = tile_left[columns+1]
	$tile_top_px  = tile_top[columns+1]
	
	# end analyze coarse map
	
	# load map
	index = 0
	count = 0
	
	castle_identifier     = '<div class="habitatContainer" style="'
	blank_identifier      = '<img src="pictures/Map/Ground'
	freecastle_identifier = $lang_f_cas
	
	freecastle_pic_identifier = []
	
	freecastle_pic_identifier.push('Castle0-N-0.png')
	freecastle_pic_identifier.push('Castle1-N-0.png')
	freecastle_pic_identifier.push('Castle2-N-0.png')
	freecastle_pic_identifier.push('Castle0N-N-0.png')
	freecastle_pic_identifier.push('Castle1N-N-0.png')
	freecastle_pic_identifier.push('Castle2N-N-0.png')
	
	castle_index = []
	blank_index  = []

	# while true fuck yeah!
	while true
		index = htmlfile.index(blank_identifier,index+1)
		if index == nil
			index = 0
			break
		end
		blank_index.push(index)
	end
	
	while true
		index = htmlfile.index(castle_identifier,index+1)
		if index == nil
			index = 0
			break
		end
		castle_index.push(index)
	end
	
	# number of tiles = rows * columns
	# in each tile are 8*8 entities ( blank space or castles )
	puts "found " + (blank_index.size + castle_index.size).to_s + " entities. it should be " + (8 * 8 * rows * columns).to_s
	
	# end load map
	
	# get name of current castle
	ccastle_identifier = '<div class="iconbutton_middle" id="btn_hab_name">'
	ccastle = findString(htmlfile,ccastle_identifier,'</div>')
		
	# end get name castle
	
	# load castles
	
	merge_list = []
	
	csize = castle_index.size
	bsize = blank_index.size
	i = 0
	j = 0
	
	# merge lists
	while (i<csize || j<bsize)
		if castle_index[i] == nil
			merge_list.push(blank_index[j])
			j = j + 1
			next
		elsif blank_index[j] == nil
			merge_list.push(castle_index[j])
			i = i + 1
			next
		elsif castle_index[i] > blank_index[j]
			merge_list.push(blank_index[j])
			j = j + 1
		else
			merge_list.push(castle_index[i])
			i = i + 1
		end
	end
	
	t = 1
	#next_tilerow_index = tile_index[t]
	#puts tile_index[1].to_s + " " + merge_list[0].to_s

	row    = rows*8
	column = columns*8	
	
	clength = castle_identifier.length
	blength = blank_identifier.length
	
	max_length = 500
	
	test_list = []
	
	local_row    = 0
	local_column = 0
	local_tile   = 0
	
	globaly = 0
	globalx = 0
	
	#file1 = File.open('order.txt', 'w')
	for k in 0 ... merge_list.size
	#for k in 0 ... 330
		#puts "k: " + k.to_s + "     "  + column.to_s  + "  "+ row.to_s
		#puts "k: " + k.to_s + "     "  + globalx.to_s  + "  "+ globaly.to_s
		
		te = row.to_s + "#" + column.to_s
		test_list << te
		
		#file1.puts column.to_s  + "  "+ row.to_s
		
		
		#this are absolute coordinates where (0/0) is at the 
		#left bottom(?) corner of the tile_map
		x_coord = column
		y_coord = row
		
		beg = merge_list[k].to_i
		#we have found a castle!
		if (htmlfile[beg+1..beg+4].to_s.include?('div') )
			en = beg + max_length.to_i
			str = htmlfile[beg..en]
			
			free_castle = str.include?(freecastle_pic_identifier[0])
			for i in 1 ... freecastle_pic_identifier.size
				free_castle = free_castle || str.include?(freecastle_pic_identifier[i])
			end
			
		
			#get tile pixel coordinates
			t_index = rows*columns-1
			for i in 0 ... tile_index.size
				if beg < tile_index[i]
					t_index = i-1
					break
				end
			end
			
			#get in tile pixel coordinates
			#this are absolute pixel coordinates where (0/0) is at the 
			#left bottom corner of the tile_map
			left_pixel = -findString(str,'" style="top:','px; left:').to_i - tile_top[t_index] + tile_top[-1]
			top_pixel = findString(str,'px; left:','px;">').to_i + tile_left[t_index]
			
			free_castle = free_castle && str.include?(freecastle_identifier)
			#we have found a free castle
			if (free_castle)
				id = findString(str,'<div id="hab_','" class="clickRectangle">')
				c = Ccastle.new(id,x_coord,y_coord,top_pixel,left_pixel)
				c.tile             = t_index
				c.tile_left        = tile_left[t_index]
				c.tile_top         = tile_top[-1]  - tile_top[t_index]
				c.globalx 		   = globalx
				c.globaly 		   = globaly
				$castles.push(c)
			#found player castle
			elsif (str.include?(ccastle) )
				$mycastle = Ccastle.new(ccastle,x_coord,y_coord,top_pixel,left_pixel)
				$mycastle.tile      = t_index
				$mycastle.tile_left = tile_left[t_index]
				$mycastle.tile_top  = tile_top[-1] - tile_top[t_index]
				$mycastle.hab_id    = findString(str,'<div id="hab_','" class="clickRectangle">')
				$mycastle.globalx   = globalx
				$mycastle.globaly   = globaly
				puts 'found player castle "' + ccastle + '"'
				#puts 'mycastle: ' + $mycastle.getx.to_s + '  ' + $mycastle.gety.to_s + '   t_index: ' + t_index.to_s + '  tile_top: ' + tile_top[t_index].to_s + ' tile_left: ' + tile_left[t_index].to_s
			end
			
			# if str.include?('196068')
				 # puts '196068  : ' + $castles[-1].getx.to_s + '  ' + $castles[-1].gety.to_s + '   t_index: ' + t_index.to_s
			 # end
			 # if str.include?('197605')
				 # puts '197605  : ' + $castles[-1].getx.to_s + '  ' + $castles[-1].gety.to_s + '   t_index: ' + t_index.to_s
			 # end
			 # if str.include?('194538')
				 # puts '194538  : ' + $castles[-1].getx.to_s + '  ' + $castles[-1].gety.to_s + '   t_index: ' + t_index.to_s
			 # end
		end
	
		
		column 		 -= 1
		row			 -= 1
		local_column += 1
		
		globalx      += 1
				
		# advance in row
		if  local_column == 8
			if (column-row).modulo(2) == 0
				row         += 7
				column      += 8
			else
				row         += 8
				column      += 9
			end
		
			globalx     -= 8
			globaly     += 1
				
			local_column = 0
			local_row   += 1
			

		end
		
		# advance in tile
		if local_row == 8
			row    -= 4
			column -= 12
		
			local_row = 0
			local_tile += 1
			
			globaly    -= 8
			globalx    += 8
		end
		
		
		# advance in tile row
		if local_tile == columns
			row    += 8*columns
			column += 8*columns
			
			row    -= 4
			column += 4
		
			local_tile = 0
			
			globalx -= 8*columns
			globaly += 8
		end
	end
	#file1.close
	
	puts 'found ' + $castles.size.to_s + ' free castles'
	
	for p in 0 ... test_list.size
		comp = test_list[p]
	   for l in p+1 ... test_list.size
			if (comp.include?(test_list[l]) && comp.size == test_list[l].size)
				puts comp + "    " + test_list[l]
				puts "something went terrible wrong!"
			end
	   end
	end
	
	unless File.directory?($castlefolder)
		puts "create folder " + $castlefolder
		Dir::mkdir($castlefolder)
	#return ccastle
	end
	
	# not yet needed
	#file = File.open($castlefolder + ccastle + '.txt', 'w')
	#for i in 0 ... $sorted.size-1
	#	file.puts $sorted[i].id
	#end
	#file.close
	$mylocation = $browser.element(:id, "hab_" + $mycastle.hab_id).wd.location
	
	# get global coordinates of current castle
	$browser.a(:title, $lang_profile).click
	sleep 2.0
	htmlfile = $browser.html
	
	index = htmlfile.index($mycastle.hab_id)
	
	str = htmlfile[index..index+60]
	habx = "habitatX:'"
	haby = ", habitatY:'"
	e = "'}"
	globalx = findString(str,habx,haby)
	globaly = findString(str,haby,e)
	#puts globalx.to_i
	#puts globaly.to_i
	
	globalx = globalx.to_i
	globaly = globaly.to_i
	
	
	for i in 0 ... $castles.size
		$castles[i].globalx -= $mycastle.globalx
		$castles[i].globaly -= $mycastle.globaly
		
		$castles[i].globalx += globalx
		$castles[i].globaly += globaly
	end
	
	sort	
	
	for i in 0 ... $sorted.size
		ishere = File.exists?($castlefolder + $sorted[i].id + $castlefileend)
		unless ishere
			file = File.open($castlefolder+ $sorted[i].id + $castlefileend, 'w')
			file << 0
			file.close
		end
	end
	

end


def init2(debug=0)
	language
	$sorted.clear
	puts "initialize all castles. this may take some time..."
	$browser.a(:title, $lang_map).click
	sleep 3.0
	htmlfile = $browser.html
	
	size = htmlfile.length
	
	tile_identifier =  '<div id="tile_'
	length = tile_identifier.length
	
	# indexing in htmlfile
	tile_index = []
	
	tile_top = []
	tile_left = []
	
	index = 0
	count = 0
	
	# extract tile line which looks like
	# <div id="tile_30" class="tileDiv" style="top:1008px;left:3024px;">
	# extracting data from tile
	while index < size
		index = htmlfile.index(tile_identifier,index+1)
		if index == nil
			break
		end
		tile_index.push(index)
		
		div_end = htmlfile.index('>',index+1)
		div_tile = htmlfile[index..div_end]

		tile_top  << findString(div_tile,'top:','px').to_i
		tile_left << findString(div_tile,'left:','px').to_i
		count = count + 1
	end
	#puts "found " + count.to_s + " tiles"
	
	# analyze coarse map
	columns = 0
	for i in 0 ... tile_top.size
		if tile_top[i] > 0
			columns = i
			break
		end
	end
	
	rows = count/columns
	puts "found " + count.to_s + " tiles with " + rows.to_s + " rows and " + columns.to_s + " columns"
	
	# end analyze coarse map
	
	# load map
	index = 0
	count = 0
	
	castle_identifier     = '<div class="habitatContainer" style="'
	blank_identifier      = '<img src="pictures/Map/Ground'
	freecastle_identifier = $lang_f_cas
	
	freecastle_pic_identifier = []
	
	freecastle_pic_identifier.push('Castle0-N-0.png')
	freecastle_pic_identifier.push('Castle1-N-0.png')
	freecastle_pic_identifier.push('Castle2-N-0.png')
	freecastle_pic_identifier.push('Castle0N-N-0.png')
	freecastle_pic_identifier.push('Castle1N-N-0.png')
	freecastle_pic_identifier.push('Castle2N-N-0.png')
	
	castle_index = []
	blank_index  = []

	# while true fuck yeah!
	while true
		index = htmlfile.index(blank_identifier,index+1)
		if index == nil
			index = 0
			break
		end
		blank_index.push(index)
	end
	
	while true
		index = htmlfile.index(castle_identifier,index+1)
		if index == nil
			index = 0
			break
		end
		castle_index.push(index)
	end
	
	# number of tiles = rows * columns
	# in each tile are 8*8 entities ( blank space or castles )
	puts "found " + (blank_index.size + castle_index.size).to_s + " entities. it should be " + (8 * 8 * rows * columns).to_s
	
	# end load map
	
	# get name of current castle
	ccastle_identifier = '<div class="iconbutton_middle" id="btn_hab_name">'
	ccastle = findString(htmlfile,ccastle_identifier,'</div>')
		
	# end get name castle
	
	# load castles
	
	merge_list = []
	
	csize = castle_index.size
	bsize = blank_index.size
	i = 0
	j = 0
	
	# merge lists
	while (i<csize || j<bsize)
		if castle_index[i] == nil
			merge_list.push(blank_index[j])
			j = j + 1
			next
		elsif blank_index[j] == nil
			merge_list.push(castle_index[j])
			i = i + 1
			next
		elsif castle_index[i] > blank_index[j]
			merge_list.push(blank_index[j])
			j = j + 1
		else
			merge_list.push(castle_index[i])
			i = i + 1
		end
	end
	
	#merge_list.push(merge_list[-1] + 534)
	merge_list[-1] = merge_list[-2] + 534
	
	file1 = File.open('map_format.txt', 'w')
	for k in 0 ... merge_list.size-1
		if k.modulo(64) == 0 && k > 0
			file1.puts ' '
		end
		string = htmlfile[merge_list[k]..merge_list[k+1]]
		string = string.gsub(/\r/," ")
		string = string.gsub(/\n/," ")
		file1.puts string
	end
	file1.close
	
end

def init_all
	language
	$player_castles = []
	$browser.a(:title, $lang_countc).click
	for i in (0..$browser.elements(:class => "castle_list").size-1) do
		text=$browser.table(:class => "castle_list", :index =>i).text
		split = text.split(/\r?\n/)
		name = split[0]
		playercastle = CPlayerCastle.new(name)
        $player_castles.push(playercastle)
        $player_castles[i].points 	= cutString(split[1])
        $player_castles[i].sp 		= cutString(split[2])
		$player_castles[i].sw 		= cutString(split[3])
        $player_castles[i].bow 		= cutString(split[4])
        $player_castles[i].cb 		= cutString(split[5])
        $player_castles[i].ar 		= cutString(split[6])      
        $player_castles[i].lr		= cutString(split[7])    
        $player_castles[i].hk 		= cutString(split[8])
        $player_castles[i].ok 		= cutString(split[9])
        $player_castles[i].wood 	= cutString(split[10])
        $player_castles[i].stone 	= cutString(split[11])                       
        $player_castles[i].ore 		= cutString(split[12])
        $player_castles[i].people 	= cutString(split[13])
        $player_castles[i].copper 	= cutString(split[14])
        $player_castles[i].silver 	= cutString(split[15])
	end
end

def cutString(string)
	if string.index(")")
		string[string.index(")")+1..-1].to_i
	else
		return string.to_i
	end
end
